<?php

namespace app\admin\controller\crm;

use app\common\controller\Backend;
use Think\Db;

/**
 * 产品管理
 *
 * @icon fa fa-circle-o
 */
class Product extends Backend
{
    
    /**
     * Product模型对象
     * @var \app\admin\model\Product
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Product;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model->alias('product')
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
            $list = $this->model->alias('product')
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            foreach ($list as $row) {
                $row->visible(['id','product','company_id','web','type']);
                /*$row->visible(['company']);
				$row->getRelation('company')->visible(['company']);*/
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     * @return string
     */
    public function add(){
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                   /* if($params['mobile']){
                        //有效
                        $params['type'] = 2;
                    }else if(empty($params['mobile'])){
                        //无效
                        $params['type'] = 1;
                    }*/
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                   /* if($params['mobile']){
                        //有效
                        $params['type'] = 2;
                    }else if(empty($params['mobile'])){
                        //无效
                        $params['type'] = 1;
                    }*/
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 查询没有推荐过给客户的产品
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function push_products(){
        $id = '';
        $param = $this->request->param();
        $param['searchValue'] = isset($param['searchValue'])?$param['searchValue']:'';//buser_id
        $param['id'] = isset($param['id'])?$param['id']:'';//buser_id
        $param['product'] = isset($param['product'])?$param['product']:'';
        if($param['searchValue']){
            $id = $param['searchValue'];
        }else if($param['id']){
            $id = $param['id'];
        }
        $linkAllot = Db::name('Allot');
        //过滤当前客户推荐过的产品
        $linkProducts = new \app\admin\model\Product;
        $pushData = $linkAllot->where(array('buser_id'=>$id))
                    ->group('product_id')->column('product_id');
        $chanWhere = array('id'=>array('NOT IN',$pushData));
        if($param['product']){
            $chanWhere['product'] = array('LIKE','%'.$param['product'].'%');
        }
        $productsData = $linkProducts->where($chanWhere)->select();
        $productsData = collection($productsData)->toArray();
        $result = array("rows" => $productsData);
        return json($result);
    }

    /**
     * 修改分配客户调用
     */
    public function edit_products(){
        $param = $this->request->param();
        $param['searchValue'] = isset($param['searchValue'])?$param['searchValue']:'';//allot_id
        $param['allot_id'] = isset($param['allot_id'])?$param['allot_id']:'';//allot_id
        $param['product'] = isset($param['product'])?$param['product']:'';
        $linkAllot = Db::name('Allot');
        $allotWhere = array();
        if($param['searchValue']){
            $allotWhere['a.id'] = $param['searchValue'];
        }else if($param['allot_id']){
            $allotWhere['a.id'] = $param['allot_id'];
        }
        $allotData =  $linkAllot->alias('a')->field('p.id AS id ,p.product AS product,a.buser_id AS buser_id')
            ->join('fa_product p','a.product_id = p.id','LEFT')
            ->where($allotWhere)->select();
        //过滤用户分配过的产品
        $allotCon = $linkAllot->where(array('buser_id'=>$allotData[0]['buser_id']))
                    ->group('product_id')->column('product_id');
        $linkProduct = Db::name('Product');
        $chanWhere = array('id'=>array('NOT IN',$allotCon));
        if($param['product']){
            $chanWhere['product'] = array('LIKE','%'.$param['product'].'%');
        }
        $data = $linkProduct->field('id ,product')->where($chanWhere)->select();
        $data = collection($data)->toArray();
        $dataArray = (!$param['product'] )?array(0=>$allotData[0]):array();
        foreach ($data as $v){
            $dataArray[] = $v;
        }
        $result = array("rows" => $dataArray);
        return json($result);
    }
}
